<script setup lang="ts">
import { message } from 'ant-design-vue'
import { useUserStore } from '@/store/modules/user-store'
import { getLodop } from '@/lib/lodop/LodopFuncs'
import { pickOrderApi } from '@/api/business/storage/picking-api'
import printModal from '@/components/business/print-modal/index.vue'

const open = ref<boolean>(false)
const emit = defineEmits(['close', 'getList'])
const userStore = useUserStore()
const visible = ref(false)

// 详情
const recordData = ref({})
const detailData = ref({})
const total_num = ref()
const time = ref()
const name = ref()
const formattedData = ref({})

const formatData = (val) => {
  const mergedData = {}
  for (const warehouseKey in val) {
    if (warehouseKey === 'create_time' || warehouseKey === 'driver_name') continue
    const warehouse = val[warehouseKey]
    const warehouseName = warehouse.out_warehouse_name
    const dealerNames = Object.keys(warehouse).filter((key) => key !== 'out_warehouse_name' && key !== 'totalLargeNum')
    mergedData[warehouseKey] = {
      warehouseKey: warehouseKey,
      warehouseName: warehouseName,
      totalLargeNum: warehouse.totalLargeNum,
      dealers: []
    }
    dealerNames.forEach((dealerName) => {
      const dealerData = warehouse[dealerName]
      const dealerInfo = {
        dealerName: dealerName,
        products: []
      }
      for (const productName in dealerData) {
        const product = dealerData[productName]
        dealerInfo.products.push({
          productName: productName,
          brand_name: product?.brand_name,
          converted_qty: product.converted_qty,
          recommend_location: product.recommend_location,
          remark: product.remark
        })
      }
      mergedData[warehouseKey].dealers.push(dealerInfo)
    })
  }
  formattedData.value = mergedData
  detailData.value = mergedData
}

async function showDrawer(record) {
  try {
    const res = await pickOrderApi.print({ id: record.id })
    const { create_time, driver_name, ...val } = res.data
    total_num.value = val.totalLargeNum
    time.value = create_time
    name.value = driver_name
    formatData(val)
    recordData.value = record
    visible.value = true
  } catch (error) {
    message.error(error.msg)
  }
}

defineExpose({
  showDrawer
})

function onClose() {
  visible.value = false
}

const usePrint = () => {
  const onPrint = () => {
    const LODOP = getLodop()
    if (!LODOP) {
      open.value = true
      return
    }
    LODOP.PRINT_INITA('0mm', '0mm', '241mm', '93mm', `拣货单`)
    LODOP.SET_PRINT_PAGESIZE(1, '215.9mm', '93mm', `拣货单`)
    let index = 0
    for (const warehouseKey in formattedData.value) {
      const warehouseData = formattedData.value[warehouseKey]
      // 使用索引作为选择器
      LODOP.ADD_PRINT_TABLE(0, '5%', '90%', '100%', document.querySelector(`#print-${index}`)?.outerHTML)
      LODOP.SET_PRINT_STYLEA(0, 'TableRowThickNess', '12pt')
      LODOP.ADD_PRINT_TEXT(0, '5%', 196, 20, '县链云仓')
      LODOP.SET_PRINT_STYLEA(0, 'ItemType', 1)
      index++
      LODOP.NewPageA()
    }
    LODOP.PREVIEW()
    pickOrderApi.detail({ id: recordData.value.id, is_print: true })
  }
  return {
    onPrint
  }
}
const { onPrint } = usePrint()
const handleModalClose = () => {
  open.value = false
}
</script>

<template>
  <printModal :open="open" @cancel="handleModalClose" />
  <a-drawer title="拣货单打印" :open="visible" @close="onClose">
    <template #closeIcon>
      <close @on-close="onClose" />
    </template>
    <div v-for="(warehouseData, warehouseKey, index) in detailData" :key="warehouseKey">
      <table :id="`print-${index}`" border="0" center cellSpacing="0" cellPadding="1" width="100%" style="border-collapse: collapse; font-size: 11pt">
        <thead>
          <tr>
            <td colspan="7">
              <div style="line-height: 30px; text-align: center; font-size: 16pt; font-weight: 700">{{ userStore.getCompanyInfo.name }}拣货单 </div>
              <font style="position: absolute; right: 0; top: 0">
                <span tdata="pageNO" format="#">#</span>
                <span>/</span>
                <span tdata="pageCount" format="#">##</span>
              </font>
            </td>
          </tr>
        </thead>
        <tbody>
          <tr>
            <td colspan="7">创建日期: {{ time }}&nbsp;&nbsp;&nbsp;&nbsp;出: {{ warehouseData.warehouseKey.replace(/\)\d+/, ')') }}&nbsp;&nbsp;&nbsp;&nbsp;入：{{ warehouseData.warehouseName }}</td>
          </tr>
          <template v-for="dealer in warehouseData.dealers" :key="dealer.dealerName">
            <tr>
              <td style="border: 1pt solid #000; font-weight: 700" colspan="5">{{ dealer.dealerName }}</td>
            </tr>
            <tr>
              <td width="10%" style="border: 1pt solid #000">
                <div align="center"><b>序号</b></div>
              </td>
              <td width="15%" style="border: 1pt solid #000">
                <div align="center"><b>品牌</b></div>
              </td>
              <td width="30%" style="border: 1pt solid #000">
                <div align="center"><b>商品名称</b></div>
              </td>
              <td width="15%" style="border: 1pt solid #000">
                <div align="center"><b>数量</b></div>
              </td>

              <td width="20%" style="border: 1pt solid #000">
                <div align="center"><b>备注</b></div>
              </td>
            </tr>
            <tr v-for="(product, index) in dealer.products" :key="product.productName">
              <td style="border: 1pt solid #000; text-align: center">
                {{ index + 1 }}
              </td>
              <td style="border: 1pt solid #000; text-align: center">{{ product.brand_name }}</td>
              <td style="border: 1pt solid #000; text-align: center">{{ product.productName }}</td>
              <td style="border: 1pt solid #000; text-align: center">{{ product.converted_qty }}</td>
              <td style="border: 1pt solid #000; text-align: center">{{ product.remark || '' }}</td>
            </tr>
          </template>
          <tr>
            <td style="border: 1pt solid #000; text-align: center">总计</td>
            <td style="border: 1pt solid #000">&nbsp;</td>
            <td style="border: 1pt solid #000">&nbsp;</td>
            <td style="border: 1pt solid #000; text-align: center">{{ warehouseData.totalLargeNum }}</td>
            <td style="border: 1pt solid #000">&nbsp;</td>
          </tr>
          <tr>
            <td colspan="3">仓管签字：</td>
            <td colspan="2">分拣员签字：</td>
          </tr>
        </tbody>
      </table>
    </div>
    <template #footer>
      <div class="flex justify-end">
        <a-button type="default" @click="onClose" style="margin-right: 8px">关闭</a-button>
        <a-button type="primary" @click="onPrint">打印</a-button>
      </div>
    </template>
  </a-drawer>
</template>
``
